package com.yshkj.payment.dto;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 基础的分页dto,返回格式为json
 * Created by 唐旭 on 2016/10/2.
 */
public abstract class PageListJsonDto<T> extends JsonBaseDto {
    public static final int DEFAULT_PAGE_SIZE = 10;
    public static final int DEFAULT_PAGE_BUTTON = 5;

    protected Map<String, Object> query = new HashMap<>();

    protected int currentPage = 1;
    protected int rowSize;
    protected long totalRecord;
    protected int totalPage;
    protected List<T> list = new ArrayList<T>();

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public int getCurrentPage() {
        if (currentPage <= 0) {
            return 1;
        }
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        if (currentPage <= 0) {
            this.currentPage = 1;
        } else {
            this.currentPage = currentPage;
        }
    }

    public int getRowSize() {
        if (rowSize > 0) {
            return rowSize;
        }
        return DEFAULT_PAGE_SIZE;
    }

    public void setRowSize(int rowSize) {
        if (rowSize <= 0) {
            this.rowSize = DEFAULT_PAGE_SIZE;
        }
        this.rowSize = rowSize;
    }

    public long getTotalRecord() {
        return totalRecord;
    }

    public void setTotalRecord(long totalRecord) {
        this.totalRecord = totalRecord;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public abstract void addAllList(List resultItem);

    public boolean isFirst() {
        return currentPage == 1;
    }

    public boolean isLast() {
        return currentPage == totalPage;
    }

    public int getBeginPageNumber() {
        int result = currentPage - (DEFAULT_PAGE_BUTTON / 2);
        return result > 0 ? result : 1;
    }

    public int getEndPageNumber() {
        int result = currentPage + (DEFAULT_PAGE_BUTTON / 2);
        return result < totalPage ? result : totalPage;
    }

    public abstract Map<String, Object> getQuery();

    public Pageable toPageable() {
        return new PageRequest(getCurrentPage() - 1, getRowSize());
    }

    public void loadList(org.springframework.data.domain.Page page) {
        this.setTotalPage(page.getTotalPages());
        this.setTotalRecord(page.getTotalElements());
        this.addAllList(page.getContent());
    }
}
